import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.Timer;


public class Game {
	private static final int scoreIncrement = 10;
	private static final Game INSTANCE = new Game();
	
	private int 	score = 0;
	
	private Board 	gameBoard;
	private GUI 	gui;
	
	//Timing stuff
	private Timer 	timer;
	private int 	timeInt = 150;
	private long 	oldTime = System.currentTimeMillis();
	private long 	newTime;
	private boolean justPressed = false;
	
	public static void main(String[] args) {
		Game.getInstance();
	}

	private Game() {
		gameBoard = new Board();
		gui 	  = new GUI(gameBoard);
		
		timer = new Timer(timeInt, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				gameLoop();
			}
		});

		timer.start();
	}
	
	public void endGame() {
		timer.stop();
	}
	
	public void score() {
		score += scoreIncrement;
		gui.updateScore(score);
	}
	
	public int getScore() {
		return score;
	}
	
	public static Game getInstance() {
		return INSTANCE;
	}

	public void gameLoop() {

		if(!gui.isPaused()){
			newTime = System.currentTimeMillis();
			int button = gui.getButton();
			//if(!justPressed){
				if(button != KeyEvent.VK_DOWN){
					timeInt = 150;
				}
				if(button == KeyEvent.VK_UP){
					//justPressed = true;
					timeInt = 150;
					//check rotate collision
					gameBoard.rotateActivePiece();
				}
				else if(button == KeyEvent.VK_LEFT){
					//justPressed = true;
					timeInt = 150;
					//check left collision
					//move left
					gameBoard.movePiece(-1); //move one to the left
				}
				else if(button == KeyEvent.VK_RIGHT){
					//justPressed = true;
					timeInt = 150;
					//check right collision
					//move right
					gameBoard.movePiece(1); //move one to the right
				}
				else if(button == KeyEvent.VK_DOWN){
					//justPressed = true;
					timeInt = 0;
				}
				else if(button == KeyEvent.VK_SPACE){
					//justPressed = true;
					timeInt = 150;
					gameBoard.instantDrop();
				}
/*			//}
			else {
				justPressed = false;
			}*/
			
			if(newTime > oldTime+timeInt){
				oldTime = newTime;
				gameBoard.dropActivePiece();
			}
			gui.showBoard();
		}
	}
}